import tkinter as tk

class Calculator:
    def __init__(self, master):
        self.master = master
        master.title("Tkinter Calculator")
        # 创建显示屏，设置宽度和字体
        self.display = tk.Entry(master, width=20, font=('Arial', 16))
        self.display.grid(row=0, column=0, columnspan=4)
        # 定义按钮布局
        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+'
        ]
        row, col = 1, 0
        for button in buttons:
            # 绑定点击事件
            cmd = lambda x=button: self.click(x)
            tk.Button(master, text=button, width=5, height=2, command=cmd).grid(row=row, column=col)
            col += 1
            if col > 3:
                col = 0
                row += 1
        # 清零按钮
        tk.Button(master, text='C', width=5, height=2, command=self.clear).grid(row=row, column=col)

    def click(self, key):
        if key == '=':
            try:
                # 计算结果
                result = eval(self.display.get())
                self.display.delete(0, tk.END)
                self.display.insert(tk.END, str(result))
            except:
                self.display.delete(0, tk.END)
                self.display.insert(tk.END, "Error")
        else:
            # 输入字符
            self.display.insert(tk.END, key)

    def clear(self):
        # 清空显示屏
        self.display.delete(0, tk.END)

root = tk.Tk()
calc = Calculator(root)
root.mainloop()